let fs = require("fs")
let path = require("path")
let config = path.resolve(__dirname, "../../config/setting.json")


exports.SaveSetting = (req, res) => {
    let newConf = { input_path, output_path, speed, bit, fps, resolving_power } = req.body;

    if (input_path && !fs.existsSync(input_path)) return res.send({ code: 400, msg: "视频加载路径不存在！" });
    if (output_path && !fs.existsSync(output_path)) return res.send({ code: 400, msg: "视频输出路径不存在！" });
    if (speed && ![1, 1.5, 2].includes(Number(speed))) return res.send({ code: 400, msg: "倍速设置不合法" });
    if (bit && !/^\d+$/.test(bit)) return res.send({ code: 400, msg: "比特速率设置不合法" });
    if (fps && !/^\d+$/.test(fps)) return res.send({ code: 400, msg: "帧率设置不合法" });
    if (resolving_power && !/^\d+\*\d+$/.test(resolving_power)) return res.send({ code: 400, msg: "分辨率格式不合法" });

    let promise = new Promise((resolve, reject) => {
        fs.readFile(config, 'utf8', (err, data) => {
            if (err) reject(err);
            resolve(JSON.parse(data));
        })
    });

    promise.then(conf => {
        // 倍速配置
        // input_path && (conf.input_path = input_path);
        // output_path && (conf.output_path = output_path);
        // speed && (conf.speed = speed);
        // // 压缩配置
        // bit && (conf.bit = bit);
        // fps && (conf.fps = fps);
        // resolving_power && (conf.resolving_power = resolving_power);

        for (const iterator in newConf) {
            if(iterator || iterator=== ''){
                conf[iterator] = newConf[iterator];
            }
        }

        fs.writeFile(config, JSON.stringify(conf), 'utf8', err => {
            if (err) return res.send({ code: 400, msg: "配置保存失败" });
            res.send({ code: 200, msg: "配置保存成功" });
        })
    })
}


exports.GetSetting = (req, res) => {
    fs.readFile(config, 'utf8', (err, data) => {
        if (err) return res.send({
            code: 404,
            msg: "获取配置失败",
            result: {}
        });
        res.send({
            code: 200,
            msg: "获取配置成功",
            result: JSON.parse(data)
        })
    })
}